package com.yjz.study.arouter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Interceptor;
import com.alibaba.android.arouter.facade.callback.InterceptorCallback;
import com.alibaba.android.arouter.facade.template.IInterceptor;
import com.yjz.study.account.AccountManager;

/**
 * 作用 : ARouter 页面拦截器
 * 作者 : yjz
 * 时间 : 2024/10/24 11:48
 */
@Interceptor(name = ARouterLogic.Interceptor.BIZ, priority = 9)
public class BizInterceptor implements IInterceptor {

    private Context context;

    @Override
    public void process(Postcard postcard, InterceptorCallback callback) {
        int flag = postcard.getExtra();
        if ((flag & RouterFlag.FLAG_LOGIN) != 0) {
            showToast("请先登录！");
            if (AccountManager.INSTANCE.isLogin()) {
                callback.onContinue(postcard);
            } else {
                AccountManager.INSTANCE.login(context, success -> {
                    if (success) {
                        callback.onContinue(postcard);
                    }
                });
            }
        } else {
            callback.onContinue(postcard);
        }
    }

    @Override
    public void init(Context context) {
        this.context = context;
    }

    public void showToast(String message) {
        new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(context, message, Toast.LENGTH_SHORT).show());
    }
}
